package cn.hpclub.server.model;

import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.Constant;

public class Business extends Model<Business>{
    public static final Business dao           = new Business();

    public final static String   ID            = "id";           // 机构主键
    public final static String   BUSINESS_CODE = "businessCode"; //
    public final static String   BUSINESS_NAME = "businessName"; //
    public final static String   PORT_URL      = "portUrl";      //
    public final static String   ENABLED       = "enabled";      //
    public final static String   REMARK        = "remark";       //
    public final static String   APPID         = "appId";        //
    public final static String   BUSINESS_TYPE = "businessType";
    public final static String   AMOUNT        = "amount";       //
    public final static String   MODULEID      = "moduleid";     //
    public final static String   IS_DELETED    = "is_deleted";   //

    public boolean checkUnique(int id, String col, String value){
        try{
            List<Record> result = Db.find("select id from " + Constant.Table.BUSIENSS + " where " + col + "=?",
                                          new Object[] { value });
            if(result.size() <= 0 || result.get(0).getInt("id") == id){

                return true;
            }

            return false;

        }
        catch(Exception e){
            e.printStackTrace();

            return true;
        }
    }

    public List<Record> getBusiness(boolean check_enabled){
        try{
            if(check_enabled){
                return Db.find("select " + ID + "," + BUSINESS_NAME + "," + BUSINESS_CODE + " from "
                        + Constant.Table.BUSIENSS + " where " + ENABLED + "=1");
            } else{
                return Db.find("select " + ID + "," + BUSINESS_NAME + "," + BUSINESS_CODE + " from "
                        + Constant.Table.BUSIENSS);
            }

        }
        catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public boolean exist(String businessCode){
        Business business = dao.findFirst("select * from " + Constant.Table.BUSIENSS + " where " + BUSINESS_CODE
                + "=? and " + ENABLED + "=1 and " + IS_DELETED + "=0", businessCode);
        if(business != null){
            return true;
        } else{
            return false;
        }
    }

    public String getName(String businessCode){

        String sql = "select " + BUSINESS_NAME + " from " + Constant.Table.BUSIENSS + " where " + BUSINESS_CODE
                + "=? and " + ENABLED + "=1 and " + IS_DELETED + "=0";
        Record r = Db.findFirst(sql, businessCode);
        return r == null ? "" : r.getStr(BUSINESS_NAME);
    }

}
